package com.heima.schedule.service.impl;

import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.schedule.service.TaskRefreshService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class TaskRefreshServiceImpl implements TaskRefreshService {

    @Autowired
    private CacheService cacheService;

    @Async("taskExecutor")
    public void refreshCache(String zsetKey) {
        //3.根据当前系统时间尝试获取key对应的zset中的任务
        Set<String> taskSet = cacheService.zRangeByScore(zsetKey, 0, DateTime.now().getMillis());

        //4.将任务从未来任务队列（zset）中删除，并添加到当前任务队列（list）中
        if(!taskSet.isEmpty()){
            String[] strArr = zsetKey.split(ScheduleConstants.FUTURE);

            String listKey = ScheduleConstants.TOPIC + strArr[1];

//                    cacheService.zRemove(zsetKey, taskSet); //将任务从未来任务队列（zset）中删除
//                    cacheService.lLeftPushAll(listKey, taskSet); //加到当前任务队列（list）中

            //基于pipeline方式执行批量从未来任务队列删除任务及从将任务批量添加到当前任务队列中
            cacheService.refreshWithPipeline(zsetKey,listKey,taskSet);
        }
    }
}
